package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.*;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.InvoiceInfoMapper;
import com.ant.storage.mapper.PurchaserRecordMapper;
import com.ant.storage.mapper.SubscribeMapper;
import com.ant.storage.mapper.SupplierInformationMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DingDingUtil;
import com.ant.storage.utils.RandomUtil;
import com.ant.storage.vo.PurchaseDetailsVo;
import com.ant.storage.vo.PurchaseVo;
import com.ant.storage.wechat.WeChatUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.ApiException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-04-13
 */
@Service
public class PurchaserRecordServiceImpl extends ServiceImpl<PurchaserRecordMapper, PurchaserRecord> implements IPurchaserRecordService {

    @Autowired
    private IPurchaserRecordService purchaserRecordService;


    @Autowired
    private IPurchaseOrdersService purchaseOrdersService;

    @Autowired
    private IPurchaserRecordImgService purchaserRecordImgService;

    @Autowired
    private ISupplierInformationService supplierInformationService;

    @Resource
    private SubscribeMapper subscribeMapper;

    @Autowired
    private ISubscribeService subscribeService;

    @Resource
    private SupplierInformationMapper supplierInformationMapper;

    @Autowired
    private ISupplierPayListService supplierPayListService;

    @Autowired
    private IMonthlySettlementService monthlySettlementService;

    @Autowired
    private IMonthlySettlementLogService monthlySettlementLogService;

    @Resource
    private IAuditListService auditListService;

    @Resource
    private IPurchaserSubscribeService purchaserSubscribeService;

    @Resource
    private IPurchaserRecordImgService imgService;

    @Resource
    private IAbilityService abilityService;

    @Autowired
    public ServletContext servletContext;

    @Resource
    private IInvoiceInfoService infoService;

    @Resource
    private InvoiceInfoMapper infoMapper;

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private IRecordOrderService recordOrderService;

    @Autowired
    public IApprovalMsgService approvalMsgService;

    @Resource
    private IReimburseDetailService detailService;
    /**
     * 单个报销申请
     *
     * @param dto
     * @param bindingResult
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo purchaserRecordSettlement(PurchaserRecordDto dto, BindingResult bindingResult) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else if (dto.getIds().size() == 0) {
            throw new AntException("请选择需要报销的订单");
        } else {
            // 判断是否已申请
            List<MonthlySettlement> parentId = monthlySettlementService.list(new QueryWrapper<MonthlySettlement>()
                    .in("supplier_pay_id", dto.getIds()));
            if (parentId.size() != 0) {
                return ResultVo.fail("已经申请结算,无效重复申请!");
            } else {
                //添加报销申请
                PurchaserRecord purchaserRecord = new PurchaserRecord();
                BeanUtils.copyProperties(dto, purchaserRecord);
                purchaserRecord.setRecordNumber("RCD" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
                purchaserRecord.setParentId(dto.getSubscribeId());
                purchaserRecord.setCreationTime(new Date());
                purchaserRecord.setCityId(userInfo.getCityId());
                this.baseMapper.insert(purchaserRecord);

                PurchaserSubscribe purchaserSubscribe = new PurchaserSubscribe();
                purchaserSubscribe.setPurchaserRecordId(purchaserRecord.getId());
                purchaserSubscribe.setSubscribeId(dto.getSubscribeId());
                purchaserSubscribe.setAmount(dto.getReimbursementAmount());
                purchaserSubscribeService.save(purchaserSubscribe);

                List<MonthlySettlement> collect = dto.getIds().stream().map(m -> {
                    MonthlySettlement monthlySettlement = new MonthlySettlement();
                    monthlySettlement.setPurchaserRecordId(purchaserRecord.getId());
                    monthlySettlement.setSupplierPayId(m);
                    return monthlySettlement;
                }).collect(Collectors.toList());
                monthlySettlementService.saveBatch(collect);
                supplierPayListService.update(new UpdateWrapper<SupplierPayList>().set("pay_status", 2).in(
                        "purchase_orders_id", dto.getIds()));
                //修改采购单的结算状态和报销状态
                subscribeService.update(new UpdateWrapper<Subscribe>()
                        .set("is_settlement", "1")
                        .set("reimbursement", "1")
                        .set("bills", dto.getImgUrlId())
                        .eq("id", dto.getSubscribeId()));
                Ability one = abilityService.getOne(new QueryWrapper<Ability>()
                        .eq("ability_key", "Nail_Approval"));
                if (one != null && one.getIsOpen()) {
                    // 添加审核
                    AuditList auditList = new AuditList();
                    auditList.setParentId(purchaserRecord.getId());
                    auditList.setProcessType("reimbursement");
                    auditList.setName(userInfo.getNameId().toString());
                    auditList.setCreationTime(new Date());
                    // 添加审核记录
                    for (String str : dto.getApproval()) {
                        auditList.setNameId(str);
                        auditList.setTypes("1");
                        auditListService.save(auditList);
                    }
                    for (String str2 : dto.getNotify()) {
                        auditList.setNameId(str2);
                        auditList.setTypes("2");
                        auditListService.save(auditList);
                    }
                    List<String> str = getImg(dto.getIds());
                    try {
                        //发起钉钉审批
                        List<Integer> ids = new ArrayList<>();
                        ids.add(dto.getSubscribeId());
                        String process_instance_id = addDingDing(dto, str, ids);
                        purchaserRecordService.update(new UpdateWrapper<PurchaserRecord>()
                                .set("process_instance_id", process_instance_id)
                                .eq("id", purchaserRecord.getId()));
                        return ResultVo.success("提交成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return ResultVo.success("提交成功");
            }
        }
    }


    /**
     * 小程序-合并报销申请
     *
     * @param recordDto
     * @param bindingResult
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo mergeSettlement(PurchaserRecordDto recordDto, BindingResult bindingResult) throws AntException {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            if (recordDto.getIds().size() > 0) {
                List<PurchaserSubscribe> purchaserSubscribes =
                        purchaserSubscribeService.list(new QueryWrapper<PurchaserSubscribe>().in(
                                "subscribe_id", recordDto.getIds()));
                if (purchaserSubscribes.size() != 0) {
                    return ResultVo.fail("已经申请结算,无效重复申请!");
                }
                PurchaserRecord purchaserRecord = new PurchaserRecord();
                BeanUtils.copyProperties(recordDto, purchaserRecord);
                purchaserRecord.setRecordNumber("RCD" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
                purchaserRecord.setParentId(recordDto.getId());
                purchaserRecord.setCreationTime(new Date());
                purchaserRecord.setCityId(userInfo.getCityId());
                purchaserRecord.setTypes(1);
                purchaserRecordService.save(purchaserRecord);
                //合并报销
                List<PurchaserSubscribe> purchaserSubscribeList = recordDto.getIds().stream().map(item -> {
                    PurchaserSubscribe purchaserSubscribe = new PurchaserSubscribe();
                    purchaserSubscribe.setSubscribeId(item);
                    purchaserSubscribe.setPurchaserRecordId(purchaserRecord.getId());
                    purchaserSubscribe.setAmount(recordDto.getReimbursementAmount());
                    purchaserSubscribe.setCreationTime(new Date());
                    return purchaserSubscribe;
                }).collect(Collectors.toList());

                purchaserSubscribeService.saveBatch(purchaserSubscribeList);
                recordDto.getIds().stream().forEach(item -> {
                    Subscribe subscribeList = subscribeMapper.selectOne(new QueryWrapper<Subscribe>().select(
                            "total").eq("id", item));
                    purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>()
                            .set("img", recordDto.getImgUrlId())
                            .set("is_settlement", 1)
                            .eq("purchaser_id", recordDto.getPurchaserId())
                            .eq("parent_id", item));
                    List<PurchaseOrders> list = purchaseOrdersService.list(new QueryWrapper<PurchaseOrders>().eq(
                            "parent_id", item)
                            .eq("is_settlement", 1));
                    if (list.size() == subscribeList.getTotal()) {
                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("reimbursement", 1)
                                .set("bills", recordDto.getImgUrlId())
                                .eq("id", item));
                    } else {
                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("bills", recordDto.getImgUrlId())
                                .eq("id", item));
                    }

                });
                //采购单状态  报销状态
                if (recordDto.getIsApproved() == 1) {
                    // 添加审核
                    AuditList auditList = new AuditList();
                    auditList.setParentId(purchaserRecord.getId());
                    auditList.setProcessType("reimbursement");
                    auditList.setName(userInfo.getNameId().toString());
                    auditList.setCreationTime(new Date());
                    // 添加审核记录
                    for (String str : recordDto.getApproval()) {
                        auditList.setNameId(str);
                        auditList.setTypes("1");
                        auditListService.save(auditList);
                    }
                    for (String str2 : recordDto.getNotify()) {
                        auditList.setNameId(str2);
                        auditList.setTypes("2");
                        auditListService.save(auditList);
                    }
                    try {
                        String str = addInvoiceInfo(purchaserRecord.getId(), recordDto.getIds(), recordDto.getRemarks(),
                                recordDto.getImgUrlId(), recordDto.getAnnexs(), recordDto.getReimbursementAmount(),
                                recordDto.getApproval(),recordDto.getNotify());
                        if(str.equals("201")){
                            throw new AntException(ResultCode.FAILURE.getResultCode(), "提交审核失败");
                        }
                        UpdateWrapper<PurchaserRecord> updateWrapper = new UpdateWrapper<PurchaserRecord>().set(
                                "process_instance_id", str).eq("id",
                                purchaserRecord.getId());
                        this.update(updateWrapper);

                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("reimbursement", 1).in("id", recordDto.getIds()));
                        return ResultVo.success("保存成功");

                    } catch (Exception e) {
                        throw new AntException(ResultCode.FAILURE.getResultCode(), "钉钉提交失败");
                    }
                }
                return ResultVo.success("提交成功");
            } else {
                throw new AntException("请选择需要报销的订单");
            }
        }
    }


    /**
     * 小程序-合并报销申请
     *
     * @param recordDto
     * @param bindingResult
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo mergeSettlements(PurchaserRecordDto recordDto, BindingResult bindingResult) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            if (recordDto.getIds().size() > 0) {
                List<PurchaserSubscribe> purchaserSubscribes =
                        purchaserSubscribeService.list(new QueryWrapper<PurchaserSubscribe>().in(
                                "subscribe_id", recordDto.getIds()));
                if (purchaserSubscribes.size() != 0) {
                    return ResultVo.fail("已经申请结算,无效重复申请!");
                }
                PurchaserRecord purchaserRecord = new PurchaserRecord();
                BeanUtils.copyProperties(recordDto, purchaserRecord);
                purchaserRecord.setRecordNumber("RCD" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
                purchaserRecord.setCreationTime(new Date());
                purchaserRecord.setCityId(userInfo.getCityId());
                purchaserRecordService.save(purchaserRecord);
                //合并报销
                List<PurchaserSubscribe> purchaserSubscribeList = recordDto.getIds().stream().map(item -> {
                    PurchaserSubscribe purchaserSubscribe = new PurchaserSubscribe();
                    purchaserSubscribe.setSubscribeId(item);
                    purchaserSubscribe.setPurchaserRecordId(purchaserRecord.getId());
                    purchaserSubscribe.setAmount(recordDto.getReimbursementAmount());
                    purchaserSubscribe.setCreationTime(new Date());
                    return purchaserSubscribe;
                }).collect(Collectors.toList());

                purchaserSubscribeService.saveBatch(purchaserSubscribeList);


                recordDto.getIds().stream().forEach(item -> {
                    Subscribe subscribeList = subscribeMapper.selectOne(new QueryWrapper<Subscribe>().select(
                            "total").eq("id", item));
                    purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>()
                            .set("img", recordDto.getImgUrlId())
                            .set("is_settlement", 1)
                            .eq("purchaser_id", recordDto.getPurchaserId())
                            .eq("parent_id", item));
                    List<PurchaseOrders> list = purchaseOrdersService.list(new QueryWrapper<PurchaseOrders>().eq(
                            "parent_id", item)
                            .eq("is_settlement", 1));
                    if (list.size() == subscribeList.getTotal()) {
                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("reimbursement", 1)
                                .set("bills", recordDto.getImgUrlId())
                                .eq("id", item));
                    } else {
                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("bills", recordDto.getImgUrlId())
                                .eq("id", item));
                    }

                });
                //采购单状态  报销状态
                if (recordDto.getIsApproved() == 1) {
                    // 添加审核
                    AuditList auditList = new AuditList();
                    auditList.setParentId(purchaserRecord.getId());
                    auditList.setProcessType("reimbursement");
                    auditList.setCreationTime(new Date());
                    // 添加审核记录
                    for (String str : recordDto.getApproval()) {
                        auditList.setNameId(str);
                        auditList.setTypes("1");
                        auditListService.save(auditList);
                    }
                    for (String str2 : recordDto.getNotify()) {
                        auditList.setNameId(str2);
                        auditList.setTypes("2");
                        auditListService.save(auditList);
                    }
                    try {
                        List<Integer> list = Arrays.asList(recordDto.getImgUrlId().split(",")).
                                stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
                        List<PurchaserRecordImg> imgList =
                                purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>()
                                        .in("id", list));
                        List<String> str = imgList.stream().map(p -> p.getUrl()).collect(Collectors.toList());
                        recordDto.setCityId(userInfo.getCityId());
                        recordDto.setUserId(userInfo.getDingTalk());
                        recordDto.setDeptId(userInfo.getDepId());

                        //采购申请钉钉审批
                        String process_instance_id = addDingDing(recordDto, str, recordDto.getIds());
                        // 修改审批id
                        if (process_instance_id.equals("201")) {
                            throw new AntException(ResultCode.FAILURE.getResultCode(), "钉钉提交失败");
                        }
                        UpdateWrapper<PurchaserRecord> updateWrapper = new UpdateWrapper<PurchaserRecord>().set(
                                "process_instance_id", process_instance_id).eq("id",
                                purchaserRecord.getId());
                        this.update(updateWrapper);

//                        addInvoiceInfo(purchaserRecord.getId(), recordDto.getIds(), recordDto.getRemarks(),
//                                recordDto.getImgUrlId(),
//                                recordDto.getAnnexs(), recordDto.getReimbursementAmount(),
//                                recordDto.getApproval(),recordDto.getNotify());

                        subscribeService.update(new UpdateWrapper<Subscribe>()
                                .set("reimbursement", 1).in("id", recordDto.getIds()));
                        return ResultVo.success("保存成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return ResultVo.success("提交成功");
            } else {
                throw new AntException("请选择需要报销的订单");
            }
        }
    }


    public List<String> getImg(List<Integer> arrs) {
        List<PurchaseOrders> list = purchaseOrdersService.list(new QueryWrapper<PurchaseOrders>()
                .select("img").in("id", arrs));
        //去重
        List<String> collect2 = list.stream().map(PurchaseOrders::getImg).distinct().collect(Collectors.toList());
        //数组转字符串
        String s = StringUtils.join(collect2, ",");
        //去重
        List<String> collect1 = Arrays.stream(s.split(",")).distinct().collect(Collectors.toList());
        //遍历获取图片路径
        List<PurchaserRecordImg> imgList = purchaserRecordImgService.list(new
                QueryWrapper<PurchaserRecordImg>().in("id", collect1));
        List<String> str = imgList.stream().map(p -> p.getUrl()).collect(Collectors.toList());
        return str;
    }


    /**
     * 合并报销获取票据
     *
     * @return
     */
    public List<String> getImgAll(PurchaserRecordDto recordDto, Integer rid) {

        List<PurchaseOrders> list = purchaseOrdersService.list(new QueryWrapper<PurchaseOrders>()
                .select("img").in("parent_id", recordDto.getIds()));

        List<MonthlySettlement> collect = list.stream().map(m -> {
            MonthlySettlement monthlySettlement = new MonthlySettlement();
            monthlySettlement.setPurchaserRecordId(rid);
            monthlySettlement.setSupplierPayId(m.getId());
            return monthlySettlement;
        }).collect(Collectors.toList());
        monthlySettlementService.saveBatch(collect);
        //集合
        List<Integer> integers = list.stream().map(PurchaseOrders::getId).distinct().collect(Collectors.toList());
        supplierPayListService.update(new UpdateWrapper<SupplierPayList>().set("pay_status", 2).in(
                "purchase_orders_id", integers));
        //去重
        List<String> collect2 = list.stream().map(PurchaseOrders::getImg).distinct().collect(Collectors.toList());
        //数组转字符串
        String s = StringUtils.join(collect2, ",");
        //字符串转集合
        List<String> collect1 = Arrays.stream(s.split(",")).distinct().collect(Collectors.toList());
        //遍历获取图片路径
        List<PurchaserRecordImg> imgList = purchaserRecordImgService.list(new
                QueryWrapper<PurchaserRecordImg>().in("id", collect1));
        List<String> str = imgList.stream().map(p -> p.getUrl()).collect(Collectors.toList());
        return str;
    }

    /**
     * 月结报销申请
     *
     * @param dto
     * @param bindingResult
     * @return
     */
    @Override
    public ResultVo MonthlySettlementSave(PurchaserRecordDto dto, BindingResult bindingResult) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            // 判断申请的采购有多少条
            List<Integer> ids = dto.getIds();
            if (ids.size() == 0) {
                return ResultVo.fail("请选择要结算的订单!!!");
            } else {
                // 判断选择的订单是否已经结算
                // 1.查询订单
                List<MonthlySettlement> record = monthlySettlementService.list(
                        new QueryWrapper<MonthlySettlement>().in("supplier_pay_id", dto.getIds()));
                if (record.size() == 0) {
                    PurchaserRecord purchaserRecord = new PurchaserRecord();
                    BeanUtils.copyProperties(dto, purchaserRecord);
                    purchaserRecord.setTypes(2); // 月结
                    purchaserRecord.setCreationTime(new Date());
                    purchaserRecordService.save(purchaserRecord);
                    //  保存月结申请
                    List<MonthlySettlement> monthlySettlementList = dto.getIds().stream().map(items -> {
                        MonthlySettlement settlement = new MonthlySettlement();
                        settlement.setSupplierPayId(items);
                        settlement.setPurchaserRecordId(purchaserRecord.getId());
                        return settlement;
                    }).collect(Collectors.toList());
                    monthlySettlementService.saveBatch(monthlySettlementList);
                    // 修改结算列表的状态
                    supplierPayListService.update(new UpdateWrapper<SupplierPayList>().set("pay_status", 2)
                            .in("purchase_orders_id", dto.getIds()));
                    //获取票据图片
                    Ability one = abilityService.getOne(new QueryWrapper<Ability>()
                            .eq("ability_key", "Nail_Approval"));
                    if (one != null && one.getIsOpen()) {
                        List<String> str = getImg(dto.getIds());
                        try {
                            dto.setUserId(userInfo.getDingTalk());
                            dto.setDeptId(userInfo.getDepId());
                            dto.setUserId(userInfo.getDingTalk());

                            String process_instance_id = addDingDing(dto, str, null);
                            if (StringUtils.isEmpty(process_instance_id)) {
                                throw new AntException(ResultCode.FAILURE.getResultCode(), "钉钉提交失败");
                            }
                            subscribeService.update(new UpdateWrapper<Subscribe>()
                                    .set("reimbursement", 2)
                                    .set("process_instance_id", process_instance_id)
                                    .in("dto.getIds()", dto.getIds()));
                            purchaserRecordService.update(new UpdateWrapper<PurchaserRecord>()
                                    .set("process_instance_id", process_instance_id)
                                    .eq("id", purchaserRecord.getId()));
                            return ResultVo.success("提交成功");
                        } catch (Exception e) {
                            e.printStackTrace();
                            return ResultVo.fail(e.getMessage());
                        }
                    }
                    return ResultVo.success("提交成功");
                } else {
                    return ResultVo.fail("已经申请结算,无需重复申请!");
                }
            }
        }
    }

    public String addDingDing(PurchaserRecordDto dto, List<String> str, List<Integer> ids) throws Exception {
        try {
            FundsDto fundsDto = new FundsDto();
            fundsDto.setAccess_token(DingDingUtil.obtainToken());
            fundsDto.setOriginator_userid(dto.getUserId());
            fundsDto.setDeptId(dto.getDeptId());
            fundsDto.setApprover_userid(dto.getApproval());
            fundsDto.setCc_userId(dto.getNotify());
            fundsDto.setDate(dto.getDate());
            fundsDto.setUrgency(dto.getUrgency());
            fundsDto.setAmount(dto.getReimbursementAmount().toString());
            fundsDto.setPicture(str);
            fundsDto.setReason(dto.getRemarks());
            fundsDto.setCompanyName(dto.getUserName());
            if (ids != null) {
                List<ReimbursementProjectDto> dataList = subscribeMapper.getids(ids);
                fundsDto.setProjectDtoList(dataList);
            }
            return DingDingUtil.Reimbursement(fundsDto);
        } catch (Exception e) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), e.getMessage());
        }

    }

    /**
     * 获取采购单结算申请列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<PurchaserRecord> getApplySettlement(PurchaserRecordDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<PurchaserRecord> wrapper = new QueryWrapper();
            if (dto.getPurchaserId() != null) {
                wrapper.eq("purchaser_id", dto.getPurchaserId());
            }
            if (StringUtils.isNotEmpty(dto.getStatues())) {
                wrapper.eq("statues", dto.getStatues());
            }
            if (StringUtils.isNotEmpty(dto.getRecordNumber())) {
                wrapper.like("record_number", dto.getRecordNumber());
            }
            if (dto.getTypes() != null) {
                wrapper.eq("types", dto.getTypes());
            }
            if (dto.getTimes() != null && dto.getTimes().size() > 0) {
                wrapper.ge("creation_time", dto.getTimes().get(0) + " 00:00:00");
                wrapper.le("creation_time", dto.getTimes().get(1) + " 23:59:59");
            }
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            if (userInfo == null) {
                wrapper.lambda().eq(PurchaserRecord::getPurchaserId, userInfo.getNameId());
            }
            if (userInfo != null && userInfo.getRoles().equals("default")) {
                wrapper.lambda().eq(PurchaserRecord::getPurchaserId, userInfo.getNameId());
            }
            if (userInfo.getRoles() != null && userInfo.getRoles().equals("admin")) {
                wrapper.lambda().in(PurchaserRecord::getCityId, userInfo.getCityId());
            }
            wrapper.ne("statues", "3");
            wrapper.orderByDesc("id");
            List<PurchaserRecord> purchaserRecordList = this.baseMapper.selectList(wrapper);

            purchaserRecordList.stream().map(item -> {
                if (item.getImgUrlId() != null && StringUtils.isNotEmpty(item.getImgUrlId())) {
                    List<Integer> idList = Arrays.stream(item.getImgUrlId().split(","))
                            .map(Integer::parseInt).collect(Collectors.toList());
                    //获取图片字符串
                    List<PurchaserRecordImg> recordImgs =
                            purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>().in("id", idList));                //过滤图片
                    String collect = recordImgs.stream().map(recordImg -> {
                        return recordImg.getUrl();
                    }).collect(Collectors.joining(","));
                    item.setImgUrlId(collect);
                }
                List<AuditList> list = auditListService.list(new QueryWrapper<AuditList>()
                        .eq("process_type", "reimbursement")
                        .eq("parent_id", item.getId()));
                item.setAuditList(list);

                return item;
            }).collect(Collectors.toList());
            PageInfo<PurchaserRecord> pageInfo = new PageInfo<>(purchaserRecordList);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(e.getMessage());
        }
    }

    @Override
    public ResultVo getApplySettlementsById(Integer id, String purchaseType) {
        if (id == null) {
            return ResultVo.fail("id不能为空!");
        } else {
            List<PurchaserRecord> list = purchaserRecordService.list(new QueryWrapper<PurchaserRecord>().eq(
                    "parent_id", id));
            if (list.size() != 0) {
                List<PurchaserRecord> collect = list.stream().map(item -> {
                    if (purchaseType.equals("18")) {
                        List<PurchaseVo> purchaseVoList =
                                this.baseMapper.getPurchaseRecordPlanById(id);
                        item.setPurchaseVo(purchaseVoList);
                    } else {
                        List<PurchaseVo> purchaseVoList =
                                this.baseMapper.getPurchaseRecordById(id);
                        item.setPurchaseVo(purchaseVoList);
                    }
                    //                    Subscribe subscribe = subscribeMapper.selectOne(new QueryWrapper<Subscribe>
                    //                    ().lambda()
                    //                            .eq(Subscribe::getId, id));
                    //                    if(subscribe.getBills()!=null){
                    //                        List<PurchaserRecordImg> recordImgList =
                    //                                recordImgService.list(new QueryWrapper<PurchaserRecordImg>().in
                    //                                ("id",
                    //                                        (subscribe.getBills().split(","))));
                    //                        item.setPurchaserRecordImgList(recordImgList);
                    //                    }
                    return item;
                }).collect(Collectors.toList());

                return ResultVo.success("查询成功", collect.get(0));
            } else {
                return ResultVo.fail("id不存在");
            }
        }
    }

    @Override
    @Transactional
    public ResultVo getApplyAdopt(PurchaserRecordDto dto) {
        //
        if (dto.getId() == null) {
            throw new AntException("id不能为空");
        } else {
            purchaserRecordService.update(new UpdateWrapper<PurchaserRecord>()
                    .set("statues", dto.getStatues())
                    .set("handlers", dto.getHandler())
                    .set("remarks", dto.getRemarks())
                    .set("handler_time", new Date())
                    .eq("id", dto.getId()));

            List<PurchaserSubscribe> purchaserRecordId =
                    purchaserSubscribeService.list(new QueryWrapper<PurchaserSubscribe>().eq("purchaser_record_id",
                            dto.getId()));
            if (purchaserRecordId.size() > 0) {
                List<Subscribe> list = purchaserRecordId.stream().map(item -> {
                    Subscribe subscribe = new Subscribe();
                    subscribe.setId(item.getSubscribeId());
                    subscribe.setReimbursement(2);
                    return subscribe;
                }).collect(Collectors.toList());
                // 是否结算 0 未结算 1 已申请  2 驳回申请 3 已结算
                subscribeService.updateBatchById(list);
            }
            return ResultVo.success("申请通过");
        }

    }

    @Override
    public PageInfo<SupplierInformation> getSupplierInformation(MonthlyDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<SupplierInformation> wrapper = new QueryWrapper();

            if (StringUtils.isNotEmpty(dto.getSupplierId())) {
                wrapper.eq("id", dto.getSupplierId());
            }
            wrapper.orderByDesc("id");
            List<SupplierInformation> supplierInformationList =
                    supplierInformationMapper.supplierInformationCensus(dto.getSupplierId());
            supplierInformationList.stream().map(item -> {
                List<SupplierPayList> list = supplierPayListService.list(new QueryWrapper<SupplierPayList>()
                        .eq("supplier_id", item.getId()));
                //统计总单量
                item.setSettlementCount(list.size());
                //统计总金额
                BigDecimal countPrice = list.stream().map(SupplierPayList::getPrice).reduce(BigDecimal.ZERO,
                        BigDecimal::add);
                item.setSettlementCountPrice(countPrice);

                //统计已结算单量
                Integer count = list.stream().filter(p -> p.getPayStatus() == 1).collect(Collectors.toList()).size();
                item.setSettlementNum(count);
                //统计已结算金额
                BigDecimal sumPrice = list.stream().filter(c -> c.getPayStatus() == 1)
                        .map(SupplierPayList::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                item.setSettlementPrice(sumPrice);

                //统计申请中单量
                Integer count1 = list.stream().filter(p -> p.getPayStatus() == 2).collect(Collectors.toList()).size();
                item.setApplyNum(count1);
                //统计申请中金额
                BigDecimal sumPrice1 = list.stream().filter(c -> c.getPayStatus() == 2)
                        .map(SupplierPayList::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                item.setApplyPrice(sumPrice1);

                return item;
            }).collect(Collectors.toList());

            PageInfo<SupplierInformation> pageInfo = new PageInfo<>(supplierInformationList);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(e.getMessage());
        }
    }


    /**
     * 月结申请 同意结算
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo MonthlySettlementAdopt(MonthlySettlementDto dto) {
        if (dto.getId() == null) {
            throw new AntException("id不能为空");
        }
        PurchaserRecord recordList = purchaserRecordService.getOne(new QueryWrapper<PurchaserRecord>().eq("id",
                dto.getId()));
        if (recordList != null) {
            // 更新申请状态
            purchaserRecordService.update(new UpdateWrapper<PurchaserRecord>()
                    .set("statues", 1)
                    .set("handlers", dto.getHandlers())
                    .set("handler_time", new Date())
                    .eq("id", dto.getId()));

            List<MonthlySettlement> list =
                    monthlySettlementService.list(new QueryWrapper<MonthlySettlement>()
                            .eq("purchaser_record_id", dto.getId()));
            // 判断NullPointerException
            try {
                //返回一个Integer集合
                List<Integer> collect =
                        list.stream().map(MonthlySettlement::getSupplierPayId).collect(Collectors.toList());
                supplierPayListService.update(new UpdateWrapper<SupplierPayList>()
                        .set("pay_status", 1)
                        .set("handle_id", Integer.valueOf(dto.getHandlers()))
                        .set("handle_time", new Date())
                        .in("purchase_orders_id", collect));
                // 添加记录
                MonthlySettlementLog monthlySettlementLog = new MonthlySettlementLog();
                monthlySettlementLog.setParentId(dto.getId());
                monthlySettlementLog.setPrice(dto.getPrice());
                monthlySettlementLog.setOpinion(dto.getOpinion());
                monthlySettlementLog.setHandleId(dto.getHandlers());
                monthlySettlementLog.setIsSettlement(dto.getIsSettlement());
                monthlySettlementLog.setHandleTime(new Date());
                monthlySettlementLogService.save(monthlySettlementLog);
                return ResultVo.success("申请通过");
            } catch (NullPointerException e) {
                e.printStackTrace();
                throw new AntException("月结申请单号不存在");
            }
            // if (list.size() > 0 && list != null) {
        } else {
            throw new AntException("数据不存在");
        }


    }

    /**
     * 财务获取月结申请
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<PurchaserRecord> getMonthlyApplySettlement(PurchaserRecordDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<PurchaserRecord> wrapper = new QueryWrapper();
            if (dto.getId() != null) {
                wrapper.eq("name_id", dto.getId());
            }
            if (dto.getSupplierId() != null) {
                wrapper.eq("supplier_id", dto.getSupplierId());
            }
            if (StringUtils.isNotEmpty(dto.getStatues())) {
                wrapper.eq("statues", dto.getStatues());
            }
            wrapper.eq("types", "2");
            wrapper.orderByDesc("id");
            List<PurchaserRecord> purchaserRecordList = this.baseMapper.selectList(wrapper);
            List<PurchaserRecord> recordList = purchaserRecordList.stream().map(item -> {
                // 供应商
                SupplierInformation supplierInformationList =
                        supplierInformationService.getOne(new QueryWrapper<SupplierInformation>()
                                .eq("id", item.getSupplierId()));
                List<SupplierPayList> supplierPayList = supplierPayListService.list(
                        new QueryWrapper<SupplierPayList>()
                                .eq("supplier_id", item.getSupplierId()));
                supplierInformationList.setSupplierPayList(supplierPayList);
                item.setSupplierInformationList(supplierInformationList);
                return item;
            }).collect(Collectors.toList());
            PageInfo<PurchaserRecord> pageInfo = new PageInfo<>(recordList);
            return pageInfo;

        } catch (Exception e) {
            throw new AntException(e.getMessage());
        }
    }

    /**
     * 通过id获取非月结单结算单详情
     *
     * @param id
     * @return
     */
    @Override
    public ResultVo getSettlementsById(Integer id) {
        if (id == null) {
            return ResultVo.fail("id不能为空!");
        } else {
            PurchaserRecord list = purchaserRecordService.getOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
            if (list != null) {
                List<PurchaseDetailsVo> purchaseVoList = null;
                if (list.getTypes() == 1) {
                    purchaseVoList = this.baseMapper.getPurchaseRecordByIdes(id);
                    purchaseVoList.removeAll(Collections.singleton(null));
                    if(purchaseVoList ==null || purchaseVoList.size()==0){
                        purchaseVoList = this.baseMapper.getPurchaseRecord(id);
                    }
                }
                if (list.getTypes() == 2) {
                    purchaseVoList = this.baseMapper.getPurchaserRecords(id);
                }
                if (purchaseVoList != null && purchaseVoList.size() > 0) {
                    //获取钉钉审核
                    List<AuditList> auditList = auditListService.list(new QueryWrapper<AuditList>().eq("parent_id", id)
                            .eq("process_type", "reimbursement"));
                    list.setAuditList(auditList);


                    ApprovalMsg approvalMsg = approvalMsgService.getOne(new QueryWrapper<ApprovalMsg>().eq("parent_id"
                            , id).eq("approval_type", "reimbursement"));
                    list.setApprovalMsgList(approvalMsg);

                    //获取票据
                    if (purchaseVoList != null) {
                        if(list.getImgUrlId() != null && list.getImgUrlId().contains(",")){
                            List<Integer> idList = Arrays.stream(list.getImgUrlId().split(","))
                                    .map(Integer::parseInt).collect(Collectors.toList());
                            List<PurchaserRecordImg> recordImgs =
                                    purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>()
                                            .in("id", idList));
                            String collect = recordImgs.stream().map(recordImg -> recordImg.getUrl())
                                    .collect(Collectors.joining(
                                            ","));
                            purchaseVoList.stream().map(item -> {
                                item.setUrl(collect);
                                return item;
                            }).collect(Collectors.toList());
                            list.setImgList(recordImgs);
                        }
                    }
                    list.setPurchaseDetailsVo(purchaseVoList);
                    return ResultVo.success("查询成功", list);
                } else {
                    return ResultVo.fail("数据不存在!!");
                }
            } else {
                return ResultVo.fail("查询失败");
            }
        }
    }

    /**
     * 小程序获取报销记录
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<PurchaserRecord> getSettlementRecord(RecordDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        List<PurchaserRecord> recordList = purchaserRecordService.list(new QueryWrapper<PurchaserRecord>()
                .eq("name_id", dto.getProposerId()).orderByDesc("id"));

        recordList.stream().map(item -> {
            if (item.getImgUrlId() != null && item.getImgUrlId().contains(",")) {
                List<Integer> idList = Arrays.stream(item.getImgUrlId().split(","))
                        .map(Integer::parseInt).collect(Collectors.toList());
                //获取图片字符串
                List<PurchaserRecordImg> recordImgs =
                        purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>()
                                .in("id", idList));                //过滤图片
                String collect = recordImgs.stream().map(recordImg -> {
                    return recordImg.getUrl();
                }).collect(Collectors.joining(","));
                item.setImgUrlId(collect);
            } else {
                if (item.getImgUrlId() != null) {
                    PurchaserRecordImg recordImg =
                            purchaserRecordImgService.getOne(new QueryWrapper<PurchaserRecordImg>()
                                    .eq("id", item.getImgUrlId()));
                    item.setImgUrlId(recordImg.getUrl());
                }
            }
            return item;
        }).collect(Collectors.toList());

        PageInfo<PurchaserRecord> pageInfo = new PageInfo<>(recordList);

        return pageInfo;
    }

    @Override
    public AuditList selectIsAudit(String processInstanceId, String user_id) {
        PurchaserRecord purchaserRecord = this.getOne(new QueryWrapper<PurchaserRecord>()
                .eq("process_instance_id", processInstanceId));
        if (purchaserRecord != null) {
            AuditList parentId = auditListService.getOne(new QueryWrapper<AuditList>()
                    .eq("parent_id", purchaserRecord.getId())
                    .eq("process_type", "reimbursement")
                    .eq("types", "1")
                    .eq("name_id", user_id));
            if (parentId != null) {
                return parentId;
            }
            return null;
        }
        return null;
    }


    /**
     * 钉钉通过审核
     *
     * @param processInstanceId
     * @param opinion
     */
    @Override
    public void recordApproved(String processInstanceId, String opinion) {
        PurchaserRecord purchaserRecord = this.getOne(new QueryWrapper<PurchaserRecord>()
                .eq("process_instance_id", processInstanceId));
        if (purchaserRecord != null) {
            if (opinion.equals("agree")) {
                this.update(new UpdateWrapper<PurchaserRecord>().set("nailing_status", "1").eq("id",
                        purchaserRecord.getId()));
                List<PurchaserSubscribe> recordId =
                        purchaserSubscribeService.list(new QueryWrapper<PurchaserSubscribe>().eq("purchaser_record_id",
                                purchaserRecord.getId()));
                if (recordId != null) {
                    recordId.stream().forEach(item -> {
                        subscribeService.update(new UpdateWrapper<Subscribe>().set("reimbursement", 2).eq("id",
                                item.getSubscribeId()));
                    });
                }
                List<RecordOrder> recordOrders =
                        recordOrderService.list(new QueryWrapper<RecordOrder>().eq("purchaser_record_id",
                                purchaserRecord.getId()));
                if (recordOrders != null) {
                    recordOrders.stream().forEach(item -> {
                        purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>().set("goods_status", 6).eq("id",
                                item.getPurchaseOrdersId()));
                    });
                }
                this.update(new UpdateWrapper<PurchaserRecord>().set("nailing_status", "1").set("statues", "1")
                        .eq("id", purchaserRecord.getId()));
            } else {
                this.update(new UpdateWrapper<PurchaserRecord>().set("nailing_status", "2").eq("id",
                        purchaserRecord.getId()));
            }
        }
    }


    /**
     * 重复企业微信
     *
     * @return
     */
    @Override
    public ResultVo RsendDingTalks(Integer id, Integer uid) throws Exception {
        UserInfo userInfo= userInfoService.getOne(new QueryWrapper<UserInfo>().eq("id", uid));
        PurchaserRecord info = this.baseMapper.selectOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
        if (info == null) {
            throw new AntException("申请记录不存在");
        }
        List<AuditList> list = auditListService.list(new QueryWrapper<AuditList>()
                .eq("process_type", "reimbursement").eq("parent_id", id));
        if (list == null) {
            throw new AntException("审核记录不存在");
        }
        List<String> approver = new ArrayList<>();
        List<String> cc = new ArrayList<>();
        if (list != null && list.size() > 0) {
            list.stream().forEach(item -> {
                if (item.getTypes().equals("1")) {
                    approver.add(item.getNameId());
                } else {
                    cc.add(item.getNameId());
                }
            });
        }

        List<RecordOrder> recordOrder = recordOrderService.list(new QueryWrapper<RecordOrder>().eq(
                "purchaser_record_id", id));
        List<Integer> ids =
                recordOrder.stream().map(item -> item.getPurchaseOrdersId()).collect(Collectors.toList());
        try {

            List<String> imgs=new ArrayList<>();
             imgs.add("3H8Rs-NskPDGAkuKvN59muGWuxnnKerHoHG-UY-oDAzpIdRBaYtTnbisSRl7SprTb");
           // imgs.add("3koud4-1JYlBmSMDzF5cRLsLx-qK6rgYKsFn59-l_GtaFODWZ0sTnbIkRSkQxqvSw"); //3071

            String str = addInvoiceInfo(info.getId(), null, info.getRemarks(), info.getImgUrlId(),
                    null, info.getReimbursementAmount(), approver, cc);
            infoService.update(new UpdateWrapper<InvoiceInfo>().set(
                    "process_instance_id", str)
                    .eq("id", id));
            PurchaserRecord r = new PurchaserRecord();
            r.setId(id);
            r.setProcessInstanceId(str);
            this.baseMapper.updateById(r);
            return ResultVo.success("提交失败");
        }catch (Exception e){
            throw new AntException(e.getMessage());
        }
    }

    public List<String> getPicture(String str) throws ApiException {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        List<Integer> list = Arrays.asList(str.split(",")).
                stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        List<PurchaserRecordImg> imgList = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                .in("id", list));
        List<String> collect = new ArrayList<>();
        if (imgList.size() <= 5) {
            imgList.stream().forEach(item -> {
                collect.add(item.getUrl());
            });
        } else {
            imgList.subList(0, 5).stream().forEach(item -> {
                collect.add(item.getUrl());
            });
        }
        //   List<String> collect = imgList.stream().map(p -> p.getUrl()).collect(Collectors.toList());
        return collect;
    }

    /**
     * @param id
     * @return
     */
    @Override
    public ResultVo getPurchaserRecordById(Integer id) {
        if (id == null) {
            return ResultVo.fail("id不能为空!");
        } else {
            PurchaserRecord list = purchaserRecordService.getOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
            if (list != null) {
                List<PurchaseDetailsVo> purchaseVoList = null;
                if (list.getTypes() == 1) {
                    purchaseVoList = this.baseMapper.getPurchaseRecordByIdes(id);
                    //移除所有的null元素
                    purchaseVoList.removeAll(Collections.singleton(null));
                    if(purchaseVoList ==null || purchaseVoList.size()==0){
                        purchaseVoList = this.baseMapper.getPurchaseRecord(id);
                    }
                }
                if (list.getTypes() == 2) {
                    purchaseVoList = this.baseMapper.getPurchaserRecordPlanned(id);
                }

                if (list.getTypes() == 4) {
                    purchaseVoList = this.baseMapper.getPurchaserRecords(id);
                }

                if (list.getImgUrlId() != null && !list.getImgUrlId().equals("")) {
                    List<Integer> idList = Arrays.stream(list.getImgUrlId().split(","))
                            .map(Integer::parseInt).collect(Collectors.toList());
                    List<PurchaserRecordImg> recordImgs =
                            purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>()
                                    .in("id", idList));
                    String collect =
                            recordImgs.stream().map(recordImg -> recordImg.getUrl()).collect(Collectors.joining(
                                    ","));
                    list.setImgUrlId(collect);
                    list.setImgList(recordImgs);
                }
                list.setPurchaseDetailsVo(purchaseVoList);
                //获取钉钉审核
                List<AuditList> auditList = auditListService.list(new QueryWrapper<AuditList>().eq("parent_id"
                        , id)
                        .eq("process_type", "reimbursement"));
                list.setAuditList(auditList);

                InvoiceInfo  info= infoService.getOne(new QueryWrapper<InvoiceInfo>()
                        .eq("house_lease_id", id).eq("reimbursement_type",25).ne("Invoice_status",4));
                if(info!=null){
                    ApprovalMsg approvalMsg = approvalMsgService.getOne(new QueryWrapper<ApprovalMsg>().eq("parent_id"
                            , info.getId()).eq("approval_type", "rent_review"));
                    if(approvalMsg!=null){
                        list.setApprovalMsgList(approvalMsg);
                    }
                }
                //获取票据
                return ResultVo.success("查询成功", list);
            } else {
                return ResultVo.fail("查询失败");
            }
        }
    }

    @Override
    public ResultVo syncDingTalk(Integer id) {
        PurchaserRecord record = this.baseMapper.selectOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
        if (record != null) {
            purchaserRecordService.update(new UpdateWrapper<PurchaserRecord>()
                    .set("nailing_status", 1)
                    .eq("id", id));
            auditListService.update(new UpdateWrapper<AuditList>()
                    .set("status", 2).eq("types", 1)
                    .eq("process_type", "reimbursement")
                    .eq("parent_id", id));
            return ResultVo.success("操作成功");
        }
        return ResultVo.fail("操作失败");
    }


    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String addInvoiceInfo(Integer rid, List<Integer> id, String remarks, String annex,
                                 List<String> annexs, BigDecimal amount,List<String> aa,List<String> cc) throws AntException {
        try {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
           // UserInfo   userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("id", 201));
            InvoiceInfo info = new InvoiceInfo();
            info.setCityId(userInfo.getCityId());
            info.setDepId(userInfo.getDepId());
            info.setWeChat(userInfo.getWeChat());
            info.setUserName(userInfo.getUserName());
            info.setHouseLeaseId(rid);
            info.setInvoiceType(2);
            info.setInvoiceNumber("QK" + RandomUtil.getOrderNumbers(infoMapper.selectLastID()));
            info.setInvoicePrice(amount);
            info.setInvoiceName("采购报销");
            info.setReimbursementType(25);
            info.setReimbursementTypeText("采购报销");
            info.setAnnex(annex);//保存本地
            info.setAnnexs(annexs);//保存企业微信
            info.setIsReimburse(1);
            info.setApproval(aa);
            info.setNotify(cc);
            info.setInvoiceNotes(remarks);
            info.setAccountUrgency("24小时完成");
            info.setCreateBy(userInfo.getNameId().toString());
            info.setCreationTime(new Date());
            info.setAccountName(null);
            info.setAccountBank(null);
            info.setAccountNumber(null);
            List<PurchaseDetailsVo> ordersList = null;
            if (id == null) {
                ordersList = this.baseMapper.getPurchaserRecords(rid);
                ordersList.removeAll(Collections.singleton(null));
                if(ordersList.size()==0){
                    ordersList = this.baseMapper.getPurchaseRecordByIdes(rid);
                }
            } else {
                ordersList = this.baseMapper.getPurchaserRecordsInIds(id);
            }
            List<ReimburseDetail> list = new ArrayList<>();
            if (ordersList != null && ordersList.size() > 0) {
                ordersList.forEach(item -> {
                    ReimburseDetail detail = new ReimburseDetail();
                    detail.setProjectName(item.getCommodityName());
                    detail.setProjectAmount(item.getCommodityAmount() == null || item.getCommodityAmount().equals("") ? "1" : item.getCommodityAmount().toString());
                    detail.setProjectUnit(item.getCommodityUnits());
                    detail.setProjectPrice(item.getCommodityPrice());
                    list.add(detail);
                });
            }
            info.setDetailList(list);
            String str = WeChatUtils.launchWeChatData(info);
            if (str != null) {
                info.setProcessInstanceId(str);
                infoService.save(info);
                if(info.getDetailList()!=null){
                    info.getDetailList().forEach(item -> {
                        ReimburseDetail detail = new ReimburseDetail();
                        detail.setProjectName(item.getProjectName());
                        detail.setProjectAmount(item.getProjectAmount() == null || item.getProjectAmount().equals("") ? "1" : item.getProjectAmount().toString());
                        detail.setProjectUnit(item.getProjectUnit());
                        detail.setProjectPrice(item.getProjectPrice());
                        detail.setParentId(info.getId());
                        detail.setParentId(info.getId());
                        detailService.save(detail);
                    });
                }
                ApprovalMsg msg = new ApprovalMsg();
                msg.setParentId(info.getId());
                msg.setApprovalType("rent_review");
                msg.setApprovalUser(userInfo.getUserName());
                msg.setApprovalUserId(userInfo.getNameId());
                msg.setSpNo(str);
                msg.setCreationTime(new Date());
                approvalMsgService.save(msg);
                return str;
            }
            return "201";
        } catch (NullPointerException e) {
            throw new AntException(ResultCode.FAILURE.getCode(), e.getMessage());
        }
    }


    @Override
    public ResultVo revoke(Integer id) {
        PurchaserRecord record = this.baseMapper.selectOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
        if (record != null) {
            record.setStatues("4");
            this.baseMapper.updateById(record);
            List<RecordOrder> recordId = recordOrderService.list(new QueryWrapper<RecordOrder>().eq(
                    "purchaser_record_id", id));
            //获取id
            List<Integer> ids =
                    recordId.stream().map(item -> item.getPurchaseOrdersId()).collect(Collectors.toList());
            purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>()
                    .set("is_settlement", 0)
                    .in("id", ids));
            return ResultVo.success("撤销成功");
        }
        return null;
    }
}
